package com.service;

import jdk.nashorn.internal.runtime.regexp.joni.Config;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 罗俊华
 * @date 2021/9/1 - 5:17 下午
 */
public class ServiceFactory {

    private final static Properties properties;

    private final static Map<Class<?>, Object> MAP;

    static {

        Map<Class<?>, Object> map = new HashMap<>();
        try (InputStream in = ServiceFactory.class.getResourceAsStream("/application.properties")) {
            properties = new Properties();
            properties.load(in);
            Set<String> names = properties.stringPropertyNames();
            for (String name : names) {
                if (name.endsWith("Service")) {
                    Class<?> interfaceClass = Class.forName(name);
                    Class<?> instanceClass = Class.forName(properties.getProperty(name));
                    map.put(interfaceClass, instanceClass.newInstance());
                }
            }
        } catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            throw new ExceptionInInitializerError(e);
        }

        MAP = Collections.unmodifiableMap(map);
    }

    @SuppressWarnings("interface-instances")
    public static <T> T getService(Class<T> interfaceClass) {
        return (T) MAP.get(interfaceClass);
    }
}
